package org.homly.tool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.Converter;


/**
 * ActionForm收集date类型数据的转换器
 * @author Administrator
 *
 */
public class DateConverter implements Converter {

	private static SimpleDateFormat sdf = new SimpleDateFormat();

	private static List<String> list = new ArrayList<String>();
	// 注册一下日期的转换格式
	static {
		DateConverter.list.add("yyyy-MM-dd HH:mm:ss");
		DateConverter.list.add("yyyy-MM-dd HH:mm");
		DateConverter.list.add("yyyy-MM-dd HH");
		DateConverter.list.add("yyyy-MM-dd");
		DateConverter.list.add("yyyy/MM/dd HH:mm:ss");
		DateConverter.list.add("yyyy/MM/dd HH:mm");
		DateConverter.list.add("yyyy/MM/dd HH");
		DateConverter.list.add("yyyy/MM/dd");
	}

	@SuppressWarnings("unchecked")
	public Object convert(Class type, Object value) {
		if (value == null) {
			return null;
		} else if (value instanceof String) {
			Object dateObj = null;
			Iterator it = list.iterator();
			while (it.hasNext()) {
				try {
					String pattern = (String) it.next();
					sdf.applyPattern(pattern);
					dateObj = sdf.parse((String)value);
					break;
				} catch (ParseException ex) {
					// do iterator continue
				}
			}
			return dateObj;
		} else {
			return null;
		}
	}
}
